/*
 * @Author: heinan
 * @Date: 2023-07-27 21:04:03
 * @Last Modified by: heinan
 * @Last Modified time: 2023-07-28 04:22:07
 */
const { OPEN_AI_APIKEY } = require("../config");

const { Configuration, OpenAIApi } = require("openai");
const configuration = new Configuration({
  apiKey: OPEN_AI_APIKEY,
});
const openai = new OpenAIApi(configuration);

// @desc openAI TEXT
// @Route POST /text
// @Access Public
const openAIText = async (req, res) => {
  const { prompt, model } = req.body;
  try {
    const result = await openai.createCompletion({
      model,
      prompt,
      temperature: 0.5,
      max_tokens: 1024,
      n: 10,
    });
    return res.json({ code: 1, result: result.data.choices });
  } catch (error) {
    if (error.response) {
      console.log(error.response.status);
      console.log(error.response.data);
      return res
        .status(error.response.status)
        .json({ code: 0, error: error.response.data });
    } else {
      console.log(error.message);
      return res.status(500).json({ code: 0, error: error.message });
    }
  }
};

// @desc openAI IMAGE
// @Route POST /image
// @Access Public
const openAIImage = async (req, res) => {
  const { prompt } = req.body;
  try {
    const result = await openai.createImage({
      prompt,
      n: 1,
      size: "512x512",
    });
    return res.json({ code: 1, result: result.data.data[0].url });
  } catch (error) {
    if (error.response) {
      console.log(error.response.status);
      console.log(error.response.data);
      return res
        .status(error.response.status)
        .json({ code: 0, error: error.response.data });
    } else {
      console.log(error.message);
      return res.status(500).json({ code: 0, error: error.message });
    }
  }
};

module.exports = { openAIText, openAIImage };
